<?php
/**
 * Created by PhpStorm.
 * User: linhongzhao
 * Date: 18-5-12
 * Time: 上午10:45
 */


define('CHARS_LOWCASE', 1);
define('CHARS_UPPERCASE', 2);
define('CHARS_UP_LOW', 3);
define('CHARS_NUMBER', 4);
define('CHARS_LOW_NUM', 5);
define('CHARS_UP_NUM', 6);
define('CHARS_UP_LOW_NUM', 7);
define('CHARS_PUNC', 8);
define('CHARS_ALL', 9);

class Random
{
    private static $references = [
        '',
        'abcdefghijklmnopqrstuvwxyz',
        'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        '0123456789',
        'abcdefghijkmnpqrstuvwxyz23456789',
        'ABCDEFGHIJKMNPQRSTUVWXY23456789',
        'abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ23456789',// 数字和字母同时出现时，抛弃loLO10，避免混淆
        ',<.>?;:[{]}|=+-_!@#$%^&*()`',// 不出现斜杠\反斜杠\单引号\双引号，避免歧义
        'abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ23456789,<.>?;:[{]}|=+-_!@#$%^&*()`',
    ];

    private static $ref_len = [
        0,
        26,
        26,
        52,
        10,
        32,
        31,
        56,
        27,
        83,
    ];

    /**
     * 产生随机字符串
     * 选择ENABLE_REPEAT后，执行效率将严重降低，但生成
     * @param int $length 字符串随机位数，默认16个字符
     * @param int 相关参数
     * @return string
     * @see Random::options()
     */
    public static function string($length = 16, $options = CHARS_UP_LOW_NUM)
    {
        $type = ($options-1 & 15) % 10 + 1;// 避免越界出错
        $refer = str_repeat(self::$references[$type], $length/self::$ref_len[$type] + 1);
        return substr(str_shuffle($refer), 0, $length);
    }

    /**
     * print defined options
     * @param bool $print
     * @return array
     */
    public static function options($print = true)
    {
        $arr = [
            'CHARS_LOWCASE' => 1,
            'CHARS_UPPERCASE' => 2,
            'CHARS_UP_LOW' => 3,
            'CHARS_NUMBER' => 4,
            'CHARS_LOW_NUM' => 5,
            'CHARS_UP_NUM' => 6,
            'CHARS_UP_LOW_NUM' => 7,
            'CHARS_PUNC' => 8,
            'CHARS_ALL' => 9,
        ];
        if ($print) {
            print_r($arr);
        }
        return $arr;
    }
}